package org.example.view;

import org.example.dao.*;
import org.example.pojo.*;
import org.example.service.AdminService;
import org.example.TablePrinter;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ManageView {
    private AdminService adminService = new AdminService();
    private LogsDao logsDao = new LogsDao();
    private AnnouncementsDao announcementsDao = new AnnouncementsDao();
    private Scanner scanner = new Scanner(System.in);

    // 显示加载动画的方法
    public void showLoadingAnimation() {
        String[] animationChars = new String[]{"|", "/", "-", "\\"};
        for (int i = 0; i < 10; i++) {
            System.out.print("\r加载中 " + animationChars[i % animationChars.length]);
        }
        System.out.println("\r加载完成!          ");
    }

    // 显示主菜单的方法
    public void showMainMenu() {
        System.out.println("\n主菜单:");
        System.out.println("1. 信息管理");
        System.out.println("2. 用户管理");
        System.out.println("0. 退出");
        System.out.print("请输入您的选择：");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                try {
                    showInfoManagementMenu();
                } catch (SQLException e) {
                    handleException(e);
                }
                break;
            case 2:
                try {
                    showUserInfoMenu();
                } catch (SQLException e) {
                    handleException(e);
                }
                break;
            case 0:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
                showMainMenu();
                break;
        }
    }

    // 显示管理员主菜单的方法
    public void showAdminMainMenu() {
        while (true) {
            System.out.println("\n管理员主菜单:");
            System.out.println("1. 信息管理");
            System.out.println("2. 用户管理");
            System.out.println("0. 退出");
            System.out.print("请输入您的选择：");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    try {
                        showInfoManagementMenu();
                    } catch (SQLException e) {
                        handleException(e);
                    }
                    break;
                case 2:
                    try {
                        showUserInfoMenu();
                    } catch (SQLException e) {
                        handleException(e);
                    }
                    break;
                case 0:
                    return; // 退出管理员主菜单
                default:
                    System.out.println("无效的选择，请重新输入！");
                    break;
            }
        }
    }

    // 显示用户信息菜单的方法
    public void showUserInfoMenu() throws SQLException {
        System.out.println("用户信息菜单:");
        System.out.println("1. 管理员信息");
        System.out.println("2. 查看所有用户");
        System.out.println("3. 查询用户");
        System.out.println("4. 删除用户");
        System.out.println("5. 查看日志");
        System.out.println("0. 返回");
        System.out.print("请输入您的选择：");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                List<Manages> manage = new SelectManage().getManage();
                TablePrinter.printTable(manage, 5, 20, 20, 15, 20, 20);
                logAction("查看管理员信息");
                break;
            case 2:
                showPaginatedUsers();
                logAction("查看所有用户");
                break;
            case 3:
                queryUser();
                logAction("查询用户");
                break;
            case 4:
                deleteUser();
                logAction("删除用户");
                break;
            case 5:
                showLogs();
                logAction("查看日志");
                break;
            case 0:
                showMainMenu();
                break;
            default:
                System.out.println("无效的选择，请重新输入！");
                showUserInfoMenu();
                break;
        }
    }

    private void showPaginatedUsers() throws SQLException {
        UsersDao usersDao = new UsersDao(); // 创建UsersDao对象
        int pageSize = 10; // 每页显示的用户数量
        int totalRecords = usersDao.getTotalUserCount(); // 获取用户总数
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize); // 计算总页数,math.cell为向上取整
        int currentPage = 1; // 当前页码

        while (true) {
            List<User> users = usersDao.getUsers(currentPage, pageSize); // 获取当前页的用户列表
            if (users.isEmpty()) { // 如果没有更多用户
                System.out.println("没有更多用户。");
                break; // 退出循环
            }
            TablePrinter.printTable(users, 5, 20, 20, 25, 15, 10, 10, 30, 20, 20); // 打印用户表格
            System.out.println("当前页: " + currentPage + " / " + totalPages); // 显示当前页码和总页数
            System.out.println("1. 下一页"); // 提示下一页选项
            System.out.println("2. 上一页"); // 提示上一页选项
            System.out.println("0. 返回"); // 提示返回选项

            String input = scanner.nextLine(); // 读取用户输入
            int choice;

            try {
                choice = Integer.parseInt(input); // 将输入转换为整数
            } catch (NumberFormatException e) {
                System.out.println("无效的输入，请输入一个数字！"); // 输入无效时提示错误
                continue; // 继续循环
            }

            if (choice == 1 && currentPage < totalPages) {
                currentPage++; // 如果选择下一页且当前页不是最后一页，页码加1
            } else if (choice == 2 && currentPage > 1) {
                currentPage--; // 如果选择上一页且当前页不是第一页，页码减1
            } else if (choice == 0) {
                break; // 如果选择返回，退出循环
            } else {
                System.out.println("无效的选择，请重新输入！"); // 选择无效时提示错误
            }
        }
    }

    private void queryUser() throws SQLException {
        UsersDao usersDao = new UsersDao(); // 创建 UsersDao 对象，用于与数据库交互
        System.out.print("请输入用户ID或用户名进行查询: "); // 提示用户输入 ID 或用户名
        String input = scanner.nextLine(); // 读取用户输入的内容
        User user;
        try {
            int id = Integer.parseInt(input); // 尝试将输入的内容转换为整数
            user = usersDao.getUserById(id); // 根据 ID 查询用户
        } catch (NumberFormatException e) {
            user = usersDao.getUserByUsername(input); // 如果转换失败，按照用户名查询用户
        }
        if (user != null) {
            List<User> userList = new ArrayList<>(); // 创建一个新的用户列表
            userList.add(user); // 将查询到的用户添加到列表中
            TablePrinter.printTable(userList, 5, 20, 20, 25, 15, 10, 10, 30, 20, 20); // 打印用户信息表格
        } else {
            System.out.println("用户未找到！"); // 如果没有找到用户，打印提示信息
        }
    }

    private void deleteUser() throws SQLException {
        UsersDao usersDao = new UsersDao();
        System.out.print("请输入要删除的用户ID: ");
        int id = scanner.nextInt();
        scanner.nextLine();
        usersDao.deleteUserById(id);
        System.out.println("用户已删除。");
    }

    //帖子表格
    public void showPostInfoMenu() throws SQLException {
        List<Posts> posts = new PostsDao().getPosts();
        printPostTable(posts);

        System.out.println("请选择操作：");
        System.out.println("1. 删除帖子");
        System.out.println("2. 修改帖子");
        System.out.println("0. 返回");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                System.out.print("请输入要删除的帖子ID: ");
                int deleteId = scanner.nextInt();
                scanner.nextLine();
                new PostsDao().deletePost(deleteId);
                System.out.println("帖子已删除。");
                break;
            case 2:
                System.out.print("请输入要修改的帖子ID: ");
                int updateId = scanner.nextInt();
                scanner.nextLine();
                System.out.print("请输入新的标题: ");
                String newTitle = scanner.nextLine();
                System.out.print("请输入新的内容: ");
                String newContent = scanner.nextLine();
                Posts post = new Posts();
                post.setId(updateId);
                post.setTitle(newTitle);
                post.setContent(newContent);
                new PostsDao().updatePost(post);
                System.out.println("帖子已更新。");
                break;
            case 0:
                // 返回上一级菜单
                showInfoManagementMenu();
                break;
            default:
                System.out.println("无效的选择，请重新输入！");
                showPostInfoMenu(); // 回到帖子信息菜单
                break;
        }
    }


    //公告菜单
    public void showAnnouncementMenu() throws SQLException {
        System.out.println("公告管理菜单:");
        System.out.println("1. 发布公告");
        System.out.println("2. 查看所有公告");
        System.out.println("3. 修改公告");
        System.out.println("4. 删除公告");
        System.out.println("0. 返回");
        System.out.print("请输入您的选择：");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                addAnnouncement();
                break;
            case 2:
                viewAnnouncements();
                break;
            case 3:
                updateAnnouncement();
                break;
            case 4:
                deleteAnnouncement();
                break;
            case 0:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
                showAnnouncementMenu();
                break;
        }
    }

    //添加公告
    private void addAnnouncement() throws SQLException {
        System.out.print("请输入公告标题：");
        String title = scanner.nextLine();
        System.out.print("请输入公告内容：");
        String content = scanner.nextLine();
        announcementsDao.addAnnouncement(title, content);
        logAction("发布公告");
        System.out.println("公告发布成功！");
    }

    //公告视图
    private void viewAnnouncements() throws SQLException {
        List<Announcement> announcements = announcementsDao.getAnnouncements();
        TablePrinter.printTable(announcements, 5, 20, 50, 20, 20);
    }

    private void updateAnnouncement() throws SQLException {
        System.out.print("请输入要修改的公告ID：");
        int id = scanner.nextInt();
        scanner.nextLine();
        System.out.print("请输入新的公告标题：");
        String title = scanner.nextLine();
        System.out.print("请输入新的公告内容：");
        String content = scanner.nextLine();
        announcementsDao.updateAnnouncement(id, title, content);
        logAction("修改公告");
        System.out.println("公告修改成功！");
    }

    private void deleteAnnouncement() throws SQLException {
        System.out.print("请输入要删除的公告ID：");
        int id = scanner.nextInt();
        scanner.nextLine();
        announcementsDao.deleteAnnouncement(id);
        logAction("删除公告");
        System.out.println("公告删除成功！");
    }

    public void showInfoManagementMenu() throws SQLException {
        System.out.println("信息管理菜单:");
        System.out.println("1. 查看帖子");
        System.out.println("2. 公告管理");
        System.out.println("0. 返回");
        System.out.print("请输入您的选择：");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                showPostInfoMenu();
                break;
            case 2:
                showAnnouncementMenu();
                break;
            case 0:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
                showInfoManagementMenu();
                break;
        }
    }

    //日志展示
    public void showLogs() throws SQLException {
        List<Log> logs = logsDao.getLogs();
        TablePrinter.printTable(logs, 5, 20, 20, 20);
    }

    private void logAction(String action) {
        try {
            logsDao.addLog(action, "管理员");
        } catch (SQLException e) {
            handleException(e);//供一个集中的异常处理机制
        }
    }

    private void handleException(Exception e) {//自定义的方法来接收一个异常参数
        System.out.println("操作失败: " + e.getMessage());
        e.printStackTrace();//用于打印异常的堆栈跟踪到标准错误流，e为最终类型
    }

    private void printPostTable(List<Posts> postList) {
        System.out.println("-------------------------------------------------------------");
        System.out.printf("%-10s %-20s %-50s %-20s %-20s\n", "ID", "标题", "内容", "创建时间", "更新时间");
        System.out.println("-------------------------------------------------------------");
        for (Posts p : postList) {
            System.out.printf("%-10d %-20s %-50s %-20s %-20s\n",
                    p.getId(), p.getTitle(), p.getContent(), p.getCreateTime(), p.getUpdateTime());
        }
        System.out.println("-------------------------------------------------------------");
    }
}